package com.start.admin.controller;

import com.start.admin.entity.StartSysMenu;
import com.start.admin.service.StartSysMenuService;
import com.start.common.api.Result;
import com.start.common.details.BaseUserDetails;
import com.start.common.entity.StartBaseMenu;
import com.start.common.utils.TreeModelUtils;
import com.start.security.StartTokenTools;
import com.start.security.StartUserPermissionTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/start/sysMenu")
public class StartSysMenuController {

    @Autowired
    private StartSysMenuService startSysMenuService;
    @Autowired
    private StartUserPermissionTools userPermissionTools;

    @GetMapping("/AllMenu")
    public Result<?> AllMenu(Boolean isTree) {
        BaseUserDetails currentUser = StartTokenTools.getCurrentUser();
        List<StartBaseMenu> userMenu = userPermissionTools.getUserMenu(currentUser);
        userMenu = userMenu.stream().sorted(Comparator.comparingInt(StartBaseMenu::getSort)).collect(Collectors.toList());
        if (isTree == null || !isTree) {
            return Result.ok(userMenu);
        }
        return Result.ok(TreeModelUtils.createTree(userMenu));
    }

    @PostMapping("/add")
    @PreAuthorize("@pas.hasPermission('sys:menu:add')")
    public Result add(@RequestBody StartSysMenu startSysMenu) {
        startSysMenuService.createMenu(startSysMenu);
        return Result.ok();
    }

    @PutMapping("/updateById")
    @PreAuthorize("@pas.hasPermission('sys:menu:edit')")
    public Result updateById(@RequestBody StartSysMenu startSysMenu) {
        startSysMenuService.updateMenuById(startSysMenu);
        return Result.ok();
    }

    @GetMapping("/getById/{id}")
    @PreAuthorize("@pas.hasPermission('sys:menu:info')")
    public Result getById(@PathVariable("id") String id) {
        return Result.ok(startSysMenuService.getById(id));
    }


    @DeleteMapping("deleteById/{id}")
    @PreAuthorize("@pas.hasPermission('sys:menu:delete')")
    public Result<?> deleteById(@PathVariable("id") String id) {
        startSysMenuService.removeById(id);
        return Result.ok();
    }

    @DeleteMapping("/deleteByIds")
    @PreAuthorize("@pas.hasPermission('sys:menu:deletes')")
    public Result<?> deleteByIds(@RequestBody String[] ids) {
        if (ids == null || ids.length < 1) return Result.ok();
        startSysMenuService.removeByIds(Arrays.asList(ids));
        return Result.ok();
    }
}
